<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">

        <!-- 搜索 -->
        <el-select
          class="main-select-tree filter-item"
          ref="selectTree"
          v-model="optionId"
          placeholder="设备位置"
          style="width: 320px;">
          <el-option v-for="item in formatData(factoryData)"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value" style="display: none;" />

          <el-tree class="main-select-el-tree" ref="selecteltree"
                   :data="factoryData"
                   node-key="id"
                   highlight-current
                   :props="defaultProps"
                   @node-click="handleNodeClick"
                   :expand-on-click-node="expandOnClickNode"
                   default-expand-all />

        </el-select>

        <el-input v-model="query.deviceCode" clearable placeholder="设备编码" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.deviceName" clearable placeholder="设备名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.deviceModel" clearable placeholder="规格型号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />

        <el-select v-model="query.monitor" clearable filterable
                   placeholder="是否监控" style="width: 185px;" class="filter-item" @change="crud.toQuery" >
          <el-option
                  v-for="item in dict.whether"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value" />
        </el-select>
        <label class="el-form-item-label">是否计算oee</label>
        <el-select v-model="query.isOee" clearable filterable
                   placeholder="请选择" style="width: 185px;" class="filter-item" @change="crud.toQuery">
          <el-option
            v-for="item in dict.whether"
            :key="item.id"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="800px">
        <el-form :inline="true" ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="设备编码" prop="deviceCode">
            <el-input v-model="form.deviceCode" style="width: 285px;" />
          </el-form-item>

          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="form.deviceName" style="width: 285px;" />
          </el-form-item>

          <el-form-item label="设备类别" prop="deviceType">
            <el-select v-model="form.deviceType" style="width: 285px;" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.device_type"
                :key="item.id"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="规格型号" prop="deviceModel">
            <el-input v-model="form.deviceModel" style="width: 285px;" />
          </el-form-item>

          <el-form-item label="选择产线" prop="lineCode">
            <el-select @change="crudLineCodeChange" v-model="form.lineCode" style="width: 285px" filterable placeholder="请选择">
              <el-option
                v-for="item in lines"
                :key="item.id"
                :label="item.modelName"
                :value="item.modelCode" >
                <span style="float: left">{{ item.modelName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.modelCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择工段" prop="sectionCode">
            <el-select @change="crudSectionCodeChange" v-model="form.sectionCode" style="width: 285px" filterable placeholder="请选择">
              <el-option
                v-for="item in sections"
                :key="item.id"
                :label="item.modelName"
                :value="item.modelCode" >
                <span style="float: left">{{ item.modelName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.modelCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="选择工位" prop="stationCode">
            <el-select v-model="form.stationCode" style="width: 285px" filterable placeholder="请选择">
              <el-option
                v-for="item in stations"
                :key="item.id"
                :label="item.modelName"
                :value="item.modelCode" >
                <span style="float: left">{{ item.modelName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.modelCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <br/>
          <el-form-item label="接收工单" prop="receiveOrder">
            <el-radio-group v-model="form.receiveOrder" style="width: 285px">
              <el-radio  v-for="item in dict.whether" :label="item.value">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否监控" prop="monitor" >
            <el-radio-group v-model="form.monitor" style="width: 285px">
              <el-radio  v-for="item in dict.whether" :label="item.value">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <br/>
          <el-form-item label="是否计算oee" prop="isOee" >
            <el-radio-group v-model="form.isOee" style="width: 285px">
              <el-radio  v-for="item in dict.whether" :label="item.value">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="生产节拍(S/个)" prop="meter">
            <el-input-number   v-model="form.meter"/>
          </el-form-item>
          <br/>
          <el-form-item label="设备图片" prop="picture">
            <el-upload
              v-if="!form.picture"
              ref="uploadImg"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="1"
              :on-change="beforeAvatarUpload"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" >
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)" >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)" >
                    <i class="el-icon-download"></i>
                  </span>
                  <span  v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)" >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>


            <ul v-if="form.picture" class="el-upload-list el-upload-list--picture-card">
              <li tabindex="0" class="el-upload-list__item is-ready">
                <div>
                  <img :src="baseApi +'/' + form.picture" alt="" class="el-upload-list__item-thumbnail">
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview2(form.picture)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload2(form.picture)">
                      <i class="el-icon-download"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove2(form.picture)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </li>
            </ul>

          </el-form-item>
          <br/>
          <el-form-item label="品牌">
            <el-input  v-model="form.brand" style="width: 285px;" />
          </el-form-item>
          <el-form-item label="单位">
            <el-input  v-model="form.unit" style="width: 285px;" />
          </el-form-item>
          <el-form-item label="供应商">
            <el-input  v-model="form.supplier" style="width: 285px;" />
          </el-form-item>
          <el-form-item label="负责人">
            <el-input  v-model="form.responsibleUser" style="width: 285px;" />
          </el-form-item>
          <el-form-item label="技术参数">
            <el-input type="textarea" :rows="3" v-model="form.technicalSpecification" style="width: 670px;" />
          </el-form-item>
          <el-form-item label="备注描述">
            <el-input type="textarea" :rows="3" v-model="form.remark" style="width: 670px;" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <!--图片查看-->
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>

      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="picture" label="设备图片" width="80" align="center" >
          <template slot-scope="scope">
            <img style="height: 30px" slot="reference" :src="getPictureUrl(scope.row)" :alt="getPictureUrl(scope.row)" class="image">
          </template>
        </el-table-column>
        <el-table-column prop="deviceCode" label="设备编码" width="150" align="center" />
        <el-table-column prop="deviceName" label="设备名称" width="150" align="center"/>
        <el-table-column prop="deviceType" label="设备类别" width="100" align="center" >
          <template slot-scope="scope">
            {{ dict.label.device_type[scope.row.deviceType] }}
          </template>
        </el-table-column>
        <el-table-column prop="deviceModel" label="规格型号" width="150" align="center"/>
        <el-table-column prop="place" label="摆放位置" width="350" align="center"/>
        <el-table-column prop="lineCode" label="产线编码" width="120" align="center"/>
        <el-table-column prop="sectionCode" label="工段编码" width="120" align="center"/>
        <el-table-column prop="stationCode" label="工位代码" width="120" align="center"/>
        <el-table-column prop="receiveOrder" label="是否接收工单" width="120" align="center">
          <template slot-scope="scope">
            {{ dict.label.whether[scope.row.receiveOrder] }}
          </template>
        </el-table-column>
        <el-table-column prop="monitor" label="是否监控" width="120" align="center">
          <template slot-scope="scope">
            {{ dict.label.whether[scope.row.monitor] }}
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="100" align="center"/>
        <el-table-column prop="brand" label="品牌" width="100" align="center"/>
        <el-table-column prop="responsibleUser" label="负责人" width="100" align="center"/>
        <el-table-column prop="supplier" label="供应商" width="100" align="center"/>
        <el-table-column prop="technicalSpecification" label="技术参数" width="220" align="center"/>
        <el-table-column prop="isOee" label="是否计算oee">
          <template slot-scope="scope">
            {{ dict.label.whether[scope.row.isOee] }}
          </template>
        </el-table-column>
        <el-table-column prop="meter" label="生产节拍"/>
        <el-table-column prop="remark" label="描述" width="220" align="center"/>
        <el-table-column prop="createBy" label="创建人" width="100" align="center"/>
        <el-table-column prop="createTime" label="创建时间" width="150" align="center"/>
        <el-table-column prop="updateBy" label="更新人" width="100" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" width="150" align="center"/>
        <el-table-column v-if="checkPer(['admin','deviceMain:edit','deviceMain:del'])" fixed="right" label="操作" width="200px" align="center">
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission">
              <router-link slot="view" :to="'/device/detail/' +scope.row.id + '/' + scope.row.deviceCode ">
                <el-button  size="mini" plain><i class="el-icon-search"></i></el-button>
              </router-link>
            </udOperation>
          </template>44
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDeviceMain from '@/api/device/deviceMain'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import crudFactoryModel from "@/api/factory/factoryModel";
import { mapGetters } from 'vuex'
import deviceImg from '@/assets/images/device1.png';

const defaultForm = { id: null, deviceCode: null, deviceName: null, deviceType: null, deviceModel: null, lineCode: null, sectionCode: null, stationCode: null, receiveOrder: '0', monitor: '1', remark: null, createBy: null, createTime: null, updateBy: null, updateTime: null,picture : null,technicalSpecification:null,   isOee:"0", meter:null, }
export default {
  name: 'DeviceMain',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['whether','device_type'],
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  watch:{
    //只能上传一张图片隐藏
    files(vaule){
      let uploadElement = document.getElementsByClassName('el-upload--picture-card')[0];
      if(uploadElement){
        if(vaule.size){
          uploadElement.classList.add("upload-hide");
        }else {
          uploadElement.classList.remove("upload-hide");
        }
      }
    },
  },
  cruds() {
    return CRUD({
      title: '设备列表',
      url: 'api/deviceMain',
      idField: 'id',
      sort: 'id,desc',
      optShow: {
        add: true,
        edit: true,
        del: true,
        download: false,
        reset: true,
        import: false
      },
      crudMethod: { ...crudDeviceMain }})
  },
  data() {
    return {
      expandOnClickNode: true,
      options:[],
      optionId: '',
      factoryData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      lines: [],
      sections: [],
      stations: [],
      files: [],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      permission: {
        add: ['admin', 'deviceMain:add'],
        edit: ['admin', 'deviceMain:edit'],
        del: ['admin', 'deviceMain:del']
      },
      rules: {
        deviceCode: [
          { required: true, message: '设备编码不能为空', trigger: 'blur' }
        ],
        deviceName: [
          { required: true, message: '设备名称不能为空', trigger: 'blur' }
        ],
        deviceType: [
          { required: true, message: '设备类别不能为空', trigger: 'blur' }
        ],
        deviceModel: [
          { required: true, message: '设备型号不能为空', trigger: 'blur' }
        ],
        lineCode: [
          { required: true, message: '产线编码不能为空', trigger: 'blur' }
        ],
        sectionCode: [
          { required: true, message: '工段编码不能为空', trigger: 'blur' }
        ],
        stationCode: [
          { required: true, message: '工位代码不能为空', trigger: 'blur' }
        ],
        receiveOrder: [
          { required: true, message: '是否接收工单不能为空', trigger: 'blur' }
        ],
        monitor: [
          { required: true, message: '是否监控不能为空', trigger: 'blur' }
        ],
        meter:[
          {required: true, message: '生产节拍不能为空', trigger: 'blur'}
        ],
        isOee:[
          {required: true, message: '是否计算oee不能为空', trigger: 'blur'}
        ]
      },
      queryTypeOptions: [
        { key: 'id', display_name: 'ID' },
        { key: 'deviceCode', display_name: '设备编码' },
        { key: 'deviceName', display_name: '设备名称' },
        { key: 'deviceType', display_name: '设备类别' },
        { key: 'deviceModel', display_name: '设备型号' },
        { key: 'lineCode', display_name: '产线编码' },
        { key: 'sectionCode', display_name: '工段编码' },
        { key: 'stationCode', display_name: '工位代码' },
        { key: 'receiveOrder', display_name: '是否接收工单' },
        { key: 'monitor', display_name: '是否监控' },
        {key: 'receiveOrder', display_name: '是否接收工单'},
        {key: 'monitor', display_name: '是否监控'}
      ]
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    //新增取消
    [CRUD.HOOK.afterAddCancel](crud) {
      this.resetForm();
      return true
    },
    //编辑取消
    [CRUD.HOOK.afterEditCancel](crud) {
      this.resetForm();
      return true
    },
    //重置之后
    [CRUD.HOOK.afterReset](crud) {
      this.optionId = '';
      return true
    },
    //提交之前
    [CRUD.HOOK.beforeSubmit](crud) {
      let formData = new FormData()
      formData.append('file', this.files)
      formData.append('data', JSON.stringify(crud.form));
      if (crud.status.add === CRUD.STATUS.PREPARED) {
        this.doAdd(crud,formData);
      } else if (crud.status.edit === CRUD.STATUS.PREPARED) {
        this.doEdit(crud,formData)
      }
      return false;
    },
    //初始化设备树
    initDeviceTree(){
      crudFactoryModel.getTreeNotDevice().then(res =>{
        this.factoryData = res;
      })
    },
    // 四级菜单
    formatData(data){
      let options = [];
      //递归解析
      this.pushOptions(options,data,'');
      this.options = options;
      return options;
    },
    //递归解析
    pushOptions(options,data,label){
      data.forEach((item,key) => {
        let name = label;
        if(name == ''){
          name = item.label;
        } else {
          name = name + "/" + item.label;
        }
        options.push({label:name,value:item.id});
        if(item.children){
          this.pushOptions(options,item.children,name);
        }
      });
    },
    handleNodeClick(node){
      this.optionId = node.id;
      this.options.forEach(item =>{
        if(item.value == node.id){
          this.query.place = item.label;
        }
      })
      this.$refs.selectTree.blur();
      this.crud.toQuery();
    },
    //刷新
    resetForm(){
      this.files = [];
      if(this.$refs.uploadImg){
        this.$refs.uploadImg.clearFiles();
      }
    },
    //添加
    doAdd(crud,formData){
      crud.status.add = CRUD.STATUS.PROCESSING
      crudDeviceMain.add(formData).then(() => {
        crud.status.add = CRUD.STATUS.NORMAL
        this.resetForm();
        crud.resetForm();
        crud.addSuccessNotify();
        crud.toQuery();
      }).catch(() => {
        crud.status.add = CRUD.STATUS.PREPARED
      })
    },
    //修改
    doEdit(crud,formData){
      crud.status.edit = CRUD.STATUS.PROCESSING
      crudDeviceMain.edit(formData).then(() => {
        crud.status.edit = CRUD.STATUS.NORMAL
        crud.getDataStatus(crud.getDataId(crud.form)).edit = CRUD.STATUS.NORMAL
        crud.editSuccessNotify()
        crud.resetForm()
        this.resetForm();
        crud.refresh()
      }).catch(() => {
        crud.status.edit = CRUD.STATUS.PREPARED
      })
    },
    //新增、修改《产线选择》
    crudLineCodeChange(lineCode){
      this.getSectionsByLineCode(lineCode);
    },
    //新增、修改《工段选择》
    crudSectionCodeChange(sectionCode){
      this.getStationsBySectionCode(sectionCode);
    },
    //获取工段信息
    getSectionsByLineCode(lineCode){
      let id = 0;
      this.lines.forEach(res => {
        if(res.modelCode == lineCode){
          id = res.id;
          return;
        }
      })
      crudFactoryModel.getModels({pid: id ,modelType: '3'}).then(res =>{
        this.sections = res.content;
      });
    },
    //获取工位信息
    getStationsBySectionCode(sectionCode){
      let id = 0;
      this.sections.forEach(res => {
        if(res.modelCode == sectionCode){
          id = res.id;
          return;
        }
      })
      crudFactoryModel.getModels({pid: id ,modelType: '4'}).then(res =>{
        this.stations = res.content;
      });
    },
    //图片上传---------------------------------
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传的工步图片大小不能超过 2MB!');
        return  isLt2M;
      }
      this.files = file.raw;
      return  isLt2M;
    },
    //新增的图片放大回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //新增的图片下载回调
    handleDownload(file) {
      let a = document.createElement("a"); //创建一个a元素
      a.href = file.url;    //a元素图片地址
      a.download = file.name; //图片名
      a.click();
    },
    //新增的图片删除回调
    handleRemove(file) {
      this.files = [];
      this.$refs.uploadImg.clearFiles();
    },
    //编辑的图片删除回调
    handleRemove2(file) {
      this.form.picture = '';
    },
    //编辑的图片放大回调
    handlePictureCardPreview2(filePath) {
      this.dialogImageUrl = this.baseApi +'/' + filePath;
      this.dialogVisible = true;
    },
    //编辑的图片下载回调
    handleDownload2(filePath) {
      let a = document.createElement("a"); //创建一个a元素
      a.href = this.baseApi +'/' + filePath;    //a元素图片地址
      a.download = '123.png'; //图片名
      a.click();
    },
    //获取图片地址
    getPictureUrl(data){
      return data.picture ? this.baseApi +'/' + data.picture :  deviceImg;
    }
  },
  mounted() {
    //加载产线
    crudFactoryModel.getModels({modelType: '2'}).then(res =>{
      this.lines = res.content;
    });
    this.initDeviceTree();
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-hide {
    display: none !important;
  }
</style>
